<script setup>
import { ref, watch } from 'vue'

// Props
const props = defineProps({
  custom: { type: Boolean, default: false },
  list: {
    type: Array,
    default: () => [
      {
        name: '新增',
        value: 'add',
        type: 'primary',
        size: 'mini',
        icon: 'Plus'
      },
      {
        name: '修改',
        value: 'edit',
        type: 'success',
        size: 'mini',
        disabled: true,
        icon: 'Edit'
      },
      {
        name: '删除',
        value: 'delete',
        type: 'danger',
        size: 'mini',
        disabled: true,
        icon: 'Delete'
      },
      {
        name: '导入',
        value: 'upload',
        type: 'info',
        size: 'mini',
        icon: 'Upload'
      },
      {
        name: '导出',
        value: 'download',
        type: 'warning',
        size: 'mini',
        icon: 'Download'
      },
      {
        name: '展开/折叠',
        value: 'toggle',
        type: 'info',
        size: 'mini',
        icon: 'Sort'
      }
    ]
  },
  layout: {
    type: String,
    default: 'add,edit,toggle,delete,upload,download,toggle'
  },
  isSelected: Boolean
})
const emit = defineEmits(['click'])

// 当前layout的按钮列表
const buttons = ref([])
const initButtons = (val) => {
  if (val) {
    buttons.value = props.list
  } else {
    if (!props.layout) {
      buttons.value = []
    } else {
      const values = props.layout.split(',').map((item) => item.trim())
      values.forEach((item) => {
        const value = props.list?.find((prop) => {
          return item === prop.value
        })
        value && buttons.value.push(value)
      })
    }
  }
}
const setButtons = (val) => {
  buttons.value.forEach((item) => {
    if (item.disabled !== undefined) {
      item.disabled = !val
    }
  })
}
watch(
  () => props.custom,
  (val) => {
    initButtons(val)
  },
  {
    immediate: true
  }
)
watch(
  () => props.isSelected,
  (val) => {
    setButtons(val)
  }
)

// 操作
const clickHandle = (item) => {
  emit('click', item)
}
</script>

<template>
  <el-row :gutter="10" class="table-buttons">
    <el-col v-for="item in buttons" :key="item.value" span="auto">
      <el-button
        :type="item.type || 'default'"
        :size="item.size || 'mini'"
        :disabled="item.disabled || false"
        :icon="item.icon"
        plain
        @click="clickHandle(item)"
      >
        {{ item.name }}
      </el-button>
    </el-col>
  </el-row>
</template>

<style lang="less" scoped></style>
